package com.gxp.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.gxp.util.common.GXPWebUtil;

public class MyMappingExceptionResolver extends SimpleMappingExceptionResolver {
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) {
		
		System.out.println("~~~~~~~~~~~~~~~~~~MyMappingExceptionResolver~~~~~~~~~~~~~~~~~~~~~~");
		String jsonObject = "";
		
		boolean isAjax = "XMLHttpRequest".equals(request
				.getHeader("X-Requested-With"));

		if (isAjax) {
			
			if (ex instanceof AccessDeniedException) {
				
				jsonObject = GXPWebUtil.handleAjaxResponse("Message.error.403", request);
				
			} else {
				jsonObject = GXPWebUtil.handleAjaxResponse("Message.error.505", request);
			}
			
			String contentType = "application/json";
			response.setContentType(contentType);
			// String jsonObject="noright";
			PrintWriter out;
			try {
				out = response.getWriter();
				out.print(jsonObject);
				out.flush();
				out.close();
				return null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

		return super.doResolveException(request, response, handler, ex);
	}

}
